package com.swhysc.information.service.impl;


import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.swhysc.information.common.model.GridView;
import com.swhysc.information.dao.IInformationDataColumnExDao;
import com.swhysc.information.entity.InformationDataColumnEx;
import com.swhysc.information.entity.QInformationDataColumnEx;
import com.swhysc.information.entity.QInformationDataDirectoryEx;
import com.swhysc.information.entity.QInformationDataTableEx;
import com.swhysc.information.repository.InformationDataColumnExRepository;
import com.swhysc.information.service.IInformationDataColumnExService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zmq
 * @Date 2022/10/14 9:38
 * @Description
 */
@Service
public class InformationDataColumnExServiceImpl implements IInformationDataColumnExService {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private InformationDataColumnExRepository informationDataColumnRepository;

    @Autowired
    private InformationDataTableExServiceImpl informationDataTableService;

    @Autowired
    private IInformationDataColumnExDao informationDataColumnDao;

    @Autowired
    private InformationDataDirExServiceImpl iInformationDataDirExService;

    @Override
    public Map getSearchList(String queryParam, String dataSourceIds, String queryType, String queryDirId, Integer page, Integer size) {
        Map<String, Object> map = new HashMap<>();
        //获取查询结果
        GridView gridView = informationDataColumnDao.searchList(queryParam, dataSourceIds, queryType, queryDirId, page, size);
        map.put("gridView",gridView);
        //获取查询个数
        if ("1".equals(queryType)){
            map.put("tableCount",gridView.getRecords());
            map.put("colCount",0);
        }else if("2".equals(queryType)){
            map.put("tableCount",0);
            map.put("colCount",gridView.getRecords());
        }else {
            QInformationDataColumnEx qInformationDataColumn = QInformationDataColumnEx.informationDataColumnEx;
            QInformationDataTableEx qInformationDataTable = QInformationDataTableEx.informationDataTableEx;
            QInformationDataDirectoryEx qInformationDataDirectory = QInformationDataDirectoryEx.informationDataDirectoryEx;
            Predicate tablePredicate = getTablePredicate(queryParam, dataSourceIds, queryDirId, qInformationDataTable);
            Predicate colPredicate = getColPredicate(queryParam, dataSourceIds, qInformationDataColumn);
            long tabelCount = jpaQueryFactory.select(qInformationDataTable.id)
                    .from(qInformationDataTable)
                    .leftJoin(qInformationDataDirectory)
                    .on(qInformationDataTable.dataSourceId.eq(qInformationDataDirectory.id))
                    .where(tablePredicate)
                    .fetchCount();
            long colCount = jpaQueryFactory.select(qInformationDataColumn.id)
                    .from(qInformationDataColumn)
                    .leftJoin(qInformationDataTable)
                    .on(qInformationDataColumn.tableId.eq(qInformationDataTable.id))
                    .leftJoin(qInformationDataDirectory)
                    .on(qInformationDataTable.dataSourceId.eq(qInformationDataDirectory.id))
                    .where(colPredicate)
                    .fetchCount();
            map.put("tableCount",tabelCount);
            map.put("colCount",colCount);
        }
        return map;
    }



    private Predicate getTablePredicate(String queryParam, String dataSourceIds, String dirId, QInformationDataTableEx qInformationDataTable) {
        //初始化查询条件，类似(where 1 = 1)
        Predicate predicate = qInformationDataTable.isNotNull().or(qInformationDataTable.isNull());
        //查询数据源
        if (StringUtils.isNotBlank(dataSourceIds)){
            predicate = ExpressionUtils.and(predicate, qInformationDataTable.dataSourceId.in(dataSourceIds.split(",")));
        }else {
            //获取当前用户已经授权的所有数据源
            /*List<InformationDataDirectoryEx> authDataSourceList = iInformationDataDirExService.getDataSource();
            List<String> authDataSourceIdList = authDataSourceList.stream().map(item -> item.getId()).collect(Collectors.toList());*/
            List<String> authDataSourceIdList = iInformationDataDirExService.getDataSourceId();
            predicate = ExpressionUtils.and(predicate, qInformationDataTable.dataSourceId.in(authDataSourceIdList));
        }
        //查询 条件
        if (StringUtils.isNotBlank(queryParam)){
            predicate = ExpressionUtils.and(predicate, qInformationDataTable.enName.likeIgnoreCase("%" + queryParam + "%")
                    .or(qInformationDataTable.chName.likeIgnoreCase("%" + queryParam + "%")));
        }
        //查询 目录
        if (StringUtils.isNotBlank(dirId)){
            List<String> dirIdList = informationDataTableService.getDirIdList(dirId);
            predicate = ExpressionUtils.and(predicate,qInformationDataTable.dirId.in(dirIdList));

        }
        return predicate;
    }

    private Predicate getColPredicate(String queryParam, String dataSourceIds, QInformationDataColumnEx qInformationDataColumn) {
        //初始化查询条件，类似(where 1 = 1)
        Predicate predicate = qInformationDataColumn.isNotNull().or(qInformationDataColumn.isNull());
        //查询数据源
        if (StringUtils.isNotBlank(dataSourceIds)){
            predicate = ExpressionUtils.and(predicate, qInformationDataColumn.dataSourceId.in(dataSourceIds.split(",")));
        }else {
            //获取当前用户已经授权的所有数据源
            /*List<InformationDataDirectoryEx> authDataSourceList = iInformationDataDirExService.getDataSource();
            List<String> authDataSourceIdList = authDataSourceList.stream().map(item -> item.getId()).collect(Collectors.toList());*/
            List<String> authDataSourceIdList = iInformationDataDirExService.getDataSourceId();
            predicate = ExpressionUtils.and(predicate, qInformationDataColumn.dataSourceId.in(authDataSourceIdList));
        }
        //查询 条件
        if (StringUtils.isNotBlank(queryParam)){
            predicate = ExpressionUtils.and(predicate, qInformationDataColumn.enName.likeIgnoreCase("%" + queryParam + "%")
                    .or(qInformationDataColumn.chName.likeIgnoreCase("%" + queryParam + "%")));
        }
        return predicate;
    }

    @Override
    public Boolean create(List<InformationDataColumnEx> informationDataColumns) {
        //校验
        Assert.isTrue(!CollectionUtils.isEmpty(informationDataColumns),"字段信息不能为空");
        for (InformationDataColumnEx informationDataColumn : informationDataColumns) {
            String enName = informationDataColumn.getEnName();
            String chName = informationDataColumn.getChName();
            String tableId = informationDataColumn.getTableId();
            Assert.isTrue(StringUtils.isNotBlank(enName),"字段英文名不能为空！");
            Assert.isTrue(StringUtils.isNotBlank(chName),"字段中文名不能为空！");
            Assert.isTrue(StringUtils.isNotBlank(tableId),"字段中文名不能为空！");
            Assert.isTrue(checkName(informationDataColumn.getId(),enName,tableId),"资讯数据字段名称重复！");
        }
        return informationDataColumnRepository.saveAll(informationDataColumns) != null;
    }

    /**
     * 名称重复校验
     * @param id
     * @param enName
     * @return
     */
    private boolean checkName(String id, String enName, String tableId) {
        QInformationDataColumnEx qInformationDataColumn = QInformationDataColumnEx.informationDataColumnEx;
        Predicate predicate = qInformationDataColumn.tableId.eq(tableId).and(qInformationDataColumn.enName.eq(enName));
        if (StringUtils.isNotBlank(id)) {
            predicate = ExpressionUtils.and(predicate, qInformationDataColumn.id.notEqualsIgnoreCase(id));
        }
        long count = jpaQueryFactory.selectFrom(qInformationDataColumn).where(predicate).fetchCount();
        return count == 0;
    }

    @Override
    public Map<String, Object> delete(String ids) {
        Assert.isTrue(StringUtils.isNotBlank(ids),"请选中要删除的字段!");
        Map<String, Object> map = new HashMap<>();
        try {
            int i = informationDataColumnRepository.deleteInformationDataColumnsByIdIn(Arrays.asList(ids.split(",")));
            map.put("falg",true);
            map.put("message","删除成功，删除" + i + "条！");
            return map;
        } catch (Exception e) {
            map.put("falg",false);
            map.put("message","删除失败！");
            e.printStackTrace();
            return map;
        }
    }

    @Override
    public List<InformationDataColumnEx> update(List<InformationDataColumnEx> informationDataColumns) {
        return null;
    }
}
